package com.wyz.module.config.security.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 无涯子
 * @date 2024/4/20
 */
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        // 获取用户信息
        Object principal = authentication.getPrincipal();
        // 用户权限信息
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        // 获取用户凭证信息
        Object credentials = authentication.getCredentials();


        Map<String,Object> map = new HashMap<>();
        map.put("code","200");
        map.put("message","登录成功");
        map.put("data", principal);

        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(map);

        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
    }
}
